package com.dwxt.cms.controller;

import com.dwxt.cms.entity.AdminUser;
import com.dwxt.cms.entity.Role;
import com.dwxt.cms.entity.dto.AdminUserDTO;
import com.dwxt.cms.entity.vo.AdminUserVO;
import com.dwxt.cms.entity.vo.MenuVO;
import com.dwxt.cms.service.UserServiceAdmin;
import com.dwxt.cms.service.feign.RedisService;
import com.dwxt.common.annotation.ValidateFiled;
import com.dwxt.common.annotation.ValidateGroup;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JwtUtils;
import com.dwxt.common.util.PartyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/admin/user")
@RestController
@Slf4j
public class UserControllerAdmin {

    @Autowired
    private UserServiceAdmin userServiceAdmin;
    @Autowired
    private RedisService redisService;

    /**
     * showdoc
     *
     * param phone    必选 string 手机号码
     * param password 必选 string 密码
     * param type     必选 int 用户类型(MALL:1,ENVIRONMENTAL_PROTECTION:2,RACE:3,ADMIN:4,MALL_ADMIN:5,MALL_TRAIN:6)
     * @return {"status":200,"msg":"SUCCESS","data":"eyJhbGciOiJIUzI1NiJ9.eyJzdGEiOjE1NzgzNjQ1MTExMTMsImV4cCI6MTU3ODM2ODExMTExMywidXNlcklkIjoyfQ.agKijFxhKrqG69d7Xw0l2i3JGNi22ZNOL6y_TPQf4b8"}
     * @catalog 后台公共部分管理/用户管理
     * @title 用户登录
     * @description 用户登录
     * @method post
     * @url /admin/user/login
     */
    @PostMapping("/login")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "phone", notNull = true),
            @ValidateFiled(index = 0, filedName = "password", notNull = true),
            @ValidateFiled(index = 0, filedName = "type", notNull = true)
    })
    public BaseResult login(AdminUser adminUser) {
        //登录次数限制
        BaseResult baseResult = redisService.get("login:" + adminUser.getPhone());
        if (baseResult.getData()!=null){
            String num=baseResult.getData().toString();
            if (num.equals("5")){
                return BaseResult.build(StatusCode.TRY_LATER);
            }else {
                redisService.set("login:" + adminUser.getPhone(),Integer.toString(Integer.parseInt(num)+1),30*60*1000L);
            }

        }else {
            redisService.set("login:"+adminUser.getPhone(),Integer.toString(1),30*60*1000L);
        }

        AdminUser user = userServiceAdmin.login(adminUser.getPhone(), adminUser.getPassword(), adminUser.getType());
        if (user != null) {
            String token = JwtUtils.createJWT(user.getId() + ",back", (long) 60 * 24 * 60 * 60 * 1000);
            return BaseResult.ok(token);
        } else {
            return BaseResult.build(StatusCode.USERNAME_PASSWORD_WRONG);
        }
    }

    /**
     * 创建或修改带角色的用户
     *
     * @param adminUserDTO
     * @return
     */
    @RequestMapping("/createOrUpdateUser")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, filedName = "phone", regStr = "^[0-9]*$"),
            //@ValidateFiled(index = 0, filedName = "roleIds", notNull = true),
    })
    public BaseResult createOrUpdateUser(AdminUserDTO adminUserDTO) {
        return userServiceAdmin.createOrUpdateUser(adminUserDTO);
        //return BaseResult.ok();
    }


    /**
     * 返回带角色的用户
     *
     * @param pageSize
     * @param pageNum
     * @return
     */
    @RequestMapping("/pageList")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true),
            @ValidateFiled(index = 1, notNull = true)
    })
    public BaseResult pageList(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminUserVO> adminUserVos = userServiceAdmin.selectAllUserVo();
        PageInfo<AdminUserVO> pageInfo = new PageInfo(adminUserVos);
        return BaseResult.ok(pageInfo);
    }


    @DeleteMapping("/delete")
    @ValidateGroup(fileds = {
            @ValidateFiled(index = 0, notNull = true)
    })
    public BaseResult delete(Integer[] id) {
        int i = userServiceAdmin.batchDeleteById(id);
        return i == 0 ? BaseResult.build(StatusCode.USER_NOT_EXIST) : BaseResult.ok();
    }

    @RequestMapping("/disOrEnable")
    public BaseResult disOrEnable(Integer id) {
        userServiceAdmin.disOrEnable(id);
        return BaseResult.ok();
    }

    /**
     * 获取用户拥有权限的菜单
     *
     * @return
     */
    @GetMapping("/menuList")
    public BaseResult menuList(Integer type) {
        String userId = PartyUtil.getCurrentUserId();
        List<MenuVO> menuVOS = userServiceAdmin.menuList(Integer.parseInt(userId), type);
        if (menuVOS.size() == 0) {
            log.error("没有权限");
            return BaseResult.build(StatusCode.PERMISSION_FAIL);
        }
        return BaseResult.ok(menuVOS);
    }

    @RequestMapping("/selectRoles")
    public BaseResult selectRoles() {
        List<Role> roleList = userServiceAdmin.selectRolesByUserId(PartyUtil.getCurrentUserId());
        return BaseResult.ok(roleList);
    }


    //返回所有的商家账户
    @RequestMapping("/selectAllMallUser")
    public BaseResult selectAllMallUser(Integer type) {
        List<AdminUser> adminUserList = userServiceAdmin.selectAllMallUser(type);
        return BaseResult.ok(adminUserList);
    }

    //返回商家账户分页
    @RequestMapping("/selectMallUserPage")
    public BaseResult selectMallUserPage(Integer pageNum, Integer pageSize, AdminUser adminUser) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminUser> adminUserList = userServiceAdmin.selectMallUserPage(adminUser);
        PageInfo<AdminUser> pageInfo = new PageInfo<>(adminUserList);
        return BaseResult.ok(pageInfo);
    }

    @RequestMapping("/selectUser")
    public BaseResult selectUser() throws InterruptedException {
        //Thread.sleep(20 * 1000);
        AdminUser adminUser = userServiceAdmin.selectUser();
        return BaseResult.ok(adminUser);
    }

    @RequestMapping("/selectUserById")
    public BaseResult selectUserById(Integer id) {
        AdminUser user = userServiceAdmin.selectUserById(id);
        return BaseResult.ok(user);
    }


    @RequestMapping("/selectAllAdminUser")
    public BaseResult selectAllAdminUser() {
        List<AdminUser> userList = userServiceAdmin.selectAllAdminUser();
        return BaseResult.ok(userList);
    }

    @RequestMapping("/selectUserHallByKey")
    public BaseResult selectUserHallByKey(Integer id) {
        return userServiceAdmin.selectUserHallByKey(id);
    }


    @RequestMapping("/selectPermissionUrl")
    public List<String> selectPermissionUrl(Integer id) {
        //System.out.println(String.format("查询支付结果......计数： %s", count.getAndAdd(1)));
        //Thread.sleep(500);
        return userServiceAdmin.getPermissionUrl(id);
    }

}